import React, { useState, useRef } from 'react';
import {
  Box,
  TextField,
  Button,
  Grid,
  Paper,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Typography,
  ToggleButton,
  ToggleButtonGroup,
  Slider,
  Tab,
  Tabs,
  IconButton,
} from '@mui/material';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import TextFieldsIcon from '@mui/icons-material/TextFields';
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome';
import FormatAlignLeftIcon from '@mui/icons-material/FormatAlignLeft';
import FormatAlignCenterIcon from '@mui/icons-material/FormatAlignCenter';
import FormatAlignRightIcon from '@mui/icons-material/FormatAlignRight';
import { toPng } from 'html-to-image';
import { saveAs } from 'file-saver';
import DecorationPanel from './decorations/DecorationPanel';
import DecorationItem from './decorations/DecorationItem';
import { useDrop } from 'react-dnd';

const templates = [
  {
    id: 'template1',
    name: '简约白',
    background: '#ffffff',
    textColor: '#000000',
    padding: '20px',
  },
  {
    id: 'template2',
    name: '粉色少女',
    background: '#fff0f5',
    textColor: '#ff69b4',
    padding: '20px',
  },
  {
    id: 'template3',
    name: 'ins风',
    background: 'linear-gradient(45deg, #f3ec78, #af4261)',
    textColor: '#ffffff',
    padding: '20px',
  },
  {
    id: 'template4',
    name: '复古胶片',
    background: '#f5e6d3',
    textColor: '#2c1810',
    padding: '20px',
    filter: 'contrast(1.1) brightness(1.1) saturate(0.9)',
  },
  {
    id: 'template5',
    name: '小清新',
    background: 'linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)',
    textColor: '#ffffff',
    padding: '20px',
  },
  {
    id: 'template6',
    name: '暖阳',
    background: 'linear-gradient(to right, #f6d365 0%, #fda085 100%)',
    textColor: '#ffffff',
    padding: '20px',
  },
  {
    id: 'template7',
    name: '夜色',
    background: 'linear-gradient(to bottom, #30cfd0 0%, #330867 100%)',
    textColor: '#ffffff',
    padding: '20px',
  },
  {
    id: 'template8',
    name: '极简黑',
    background: '#000000',
    textColor: '#ffffff',
    padding: '20px',
  },
  {
    id: 'template9',
    name: '薄荷绿',
    background: '#E0F4F1',
    textColor: '#00796B',
    padding: '20px',
  },
  {
    id: 'template10',
    name: '珊瑚粉',
    background: '#FFE4E1',
    textColor: '#FF6B6B',
    padding: '20px',
  },
  {
    id: 'template11',
    name: '霓虹夜景',
    background: 'linear-gradient(to right, #0f2027, #203a43, #2c5364)',
    textColor: '#00ff00',
    padding: '20px',
    textShadow: '0 0 10px #00ff00, 0 0 20px #00ff00, 0 0 30px #00ff00',
  },
  {
    id: 'template12',
    name: '赛博朋克',
    background: 'linear-gradient(45deg, #000000, #1a1a1a)',
    textColor: '#ff00ff',
    padding: '20px',
    textShadow: '2px 2px 0 #00ffff',
    borderStyle: 'solid',
    borderWidth: '2px',
    borderImage: 'linear-gradient(45deg, #ff00ff, #00ffff) 1',
  },
  {
    id: 'template13',
    name: '日系杂志',
    background: '#f4f4f4',
    textColor: '#333333',
    padding: '30px',
    borderLeft: '4px solid #000',
    fontFamily: '"Noto Sans JP", sans-serif',
  },
  {
    id: 'template14',
    name: '水彩画布',
    background: 'linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%)',
    textColor: '#4a4a4a',
    padding: '20px',
    filter: 'opacity(0.9)',
  },
  {
    id: 'template15',
    name: '莫兰迪',
    background: '#e6e2dd',
    textColor: '#7c7c7c',
    padding: '20px',
    filter: 'saturate(0.8)',
  },
  {
    id: 'template16',
    name: '星空梦幻',
    background: 'linear-gradient(to bottom, #000000, #434343)',
    textColor: '#ffffff',
    padding: '20px',
    backgroundImage: 'radial-gradient(circle at center, #ffffff 1px, transparent 1px)',
    backgroundSize: '30px 30px',
  },
  {
    id: 'template17',
    name: '甜甜圈',
    background: 'linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)',
    textColor: '#ffffff',
    padding: '20px',
    borderRadius: '15px',
    boxShadow: '0 4px 15px rgba(0,0,0,0.1)',
  },
  {
    id: 'template18',
    name: '极光',
    background: 'linear-gradient(to right, #43c6ac, #191654)',
    textColor: '#ffffff',
    padding: '20px',
    filter: 'brightness(1.1)',
  },
  {
    id: 'template19',
    name: '下午茶',
    background: '#faf3e0',
    textColor: '#7c5c3c',
    padding: '20px',
    borderStyle: 'dotted',
    borderWidth: '2px',
    borderColor: '#d4b595',
  },
  {
    id: 'template20',
    name: '城市街拍',
    background: '#2c3e50',
    textColor: '#ecf0f1',
    padding: '20px',
    filter: 'contrast(1.1)',
    boxShadow: 'inset 0 0 50px rgba(0,0,0,0.5)',
  }
];

const aspectRatios = [
  { id: '1:1', value: '1/1', name: '方形 1:1' },
  { id: '3:4', value: '3/4', name: '小红书 3:4' },
  { id: '9:16', value: '9/16', name: '竖屏 9:16' },
];

const fonts = [
  { id: 'default', name: '默认字体', value: '"PingFang SC", "Microsoft YaHei", sans-serif' },
  { id: 'songti', name: '宋体', value: 'SimSun, serif' },
  { id: 'kaiti', name: '楷体', value: 'KaiTi, serif' },
  { id: 'heiti', name: '黑体', value: 'SimHei, sans-serif' },
];

const fontSizes = [
  { id: 'small', name: '小', value: '18px' },
  { id: 'medium', name: '中', value: '24px' },
  { id: 'large', name: '大', value: '32px' },
  { id: 'xlarge', name: '特大', value: '42px' },
];

const textAlignments = [
  { id: 'left', icon: <FormatAlignLeftIcon />, value: 'left' },
  { id: 'center', icon: <FormatAlignCenterIcon />, value: 'center' },
  { id: 'right', icon: <FormatAlignRightIcon />, value: 'right' },
];

function ImageEditor() {
  const [text, setText] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState(templates[0]);
  const [aspectRatio, setAspectRatio] = useState(aspectRatios[1]);
  const [selectedFont, setSelectedFont] = useState(fonts[0]);
  const [selectedFontSize, setSelectedFontSize] = useState(fontSizes[1]);
  const [textColor, setTextColor] = useState('#000000');
  const [textAlign, setTextAlign] = useState('center');
  const [letterSpacing, setLetterSpacing] = useState(0);
  const [lineHeight, setLineHeight] = useState(1.5);
  const [textShadow, setTextShadow] = useState(false);
  const [textShadowColor, setTextShadowColor] = useState('#000000');
  const [decorations, setDecorations] = useState([]);
  const [isPanelOpen, setIsPanelOpen] = useState(true);
  const [currentTab, setCurrentTab] = useState(0);
  const imageRef = useRef(null);

  const handleTextChange = (event) => {
    setText(event.target.value);
  };

  const handleTemplateChange = (event) => {
    const template = templates.find(t => t.id === event.target.value);
    setSelectedTemplate(template);
  };

  const handleAspectRatioChange = (event) => {
    const ratio = aspectRatios.find(r => r.id === event.target.value);
    setAspectRatio(ratio);
  };

  const handleFontChange = (event) => {
    const font = fonts.find(f => f.id === event.target.value);
    setSelectedFont(font);
  };

  const handleFontSizeChange = (event) => {
    const fontSize = fontSizes.find(f => f.id === event.target.value);
    setSelectedFontSize(fontSize);
  };

  const handleTextColorChange = (event) => {
    setTextColor(event.target.value);
  };

  const handleTextAlignChange = (event, newAlignment) => {
    if (newAlignment !== null) {
      setTextAlign(newAlignment);
    }
  };

  const handleLetterSpacingChange = (event, newValue) => {
    setLetterSpacing(newValue);
  };

  const handleLineHeightChange = (event, newValue) => {
    setLineHeight(newValue);
  };

  const handleTextShadowToggle = () => {
    setTextShadow(!textShadow);
  };

  const handleTextShadowColorChange = (event) => {
    setTextShadowColor(event.target.value);
  };

  const handleDownload = async () => {
    if (imageRef.current) {
      const dataUrl = await toPng(imageRef.current);
      saveAs(dataUrl, 'red-book-image.png');
    }
  };

  const handleTabChange = (event, newValue) => {
    setCurrentTab(newValue);
  };

  const [, drop] = useDrop(() => ({
    accept: 'decoration',
    drop: (item, monitor) => {
      const dropOffset = monitor.getClientOffset();
      const containerRect = imageRef.current.getBoundingClientRect();
      const scale = containerRect.width / 100; // 使用容器宽度作为基准计算缩放比例
      
      // 计算相对于容器的位置，并转换为百分比
      const x = (dropOffset.x - containerRect.left) / scale;
      const y = (dropOffset.y - containerRect.top) / scale;

      // 为新装饰元素创建唯一ID
      const newDecoration = {
        ...item,
        id: `${item.id}-${Date.now()}`,
        position: { x, y },
        scale: 1,
        rotation: 0,
      };

      // 添加新的装饰元素到数组中
      setDecorations(prev => [...prev, newDecoration]);
    },
  }));

  return (
    <Box sx={{ display: 'flex', height: 'calc(100vh - 100px)' }}>
      <Box
        sx={{
          flexGrow: 1,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          p: 3,
          backgroundColor: '#f5f5f5',
        }}
      >
        <Paper
          ref={(node) => {
            imageRef.current = node;
            drop(node);
          }}
          sx={{
            width: '100%',
            maxWidth: '600px',
            aspectRatio: aspectRatio.value,
            background: selectedTemplate.background,
            color: textColor,
            padding: selectedTemplate.padding,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            textAlign: textAlign,
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
            fontSize: selectedFontSize.value,
            fontFamily: selectedFont.value,
            letterSpacing: `${letterSpacing}px`,
            lineHeight: lineHeight,
            textShadow: textShadow ? `2px 2px 4px ${textShadowColor}` : 'none',
            position: 'relative',
            overflow: 'hidden',
          }}
        >
          {text || '在左侧输入文字预览效果'}
          {decorations.map((decoration) => (
            <DecorationItem
              key={decoration.id}
              item={decoration}
              onDelete={() => {
                setDecorations(decorations.filter(d => d.id !== decoration.id));
              }}
              onUpdate={(updatedDecoration) => {
                setDecorations(decorations.map(d => 
                  d.id === updatedDecoration.id ? updatedDecoration : d
                ));
              }}
            />
          ))}
        </Paper>
      </Box>

      <Box sx={{ position: 'relative' }}>
        <IconButton
          size="small"
          onClick={() => setIsPanelOpen(!isPanelOpen)}
          sx={{
            position: 'absolute',
            left: '-20px',
            top: '50%',
            transform: 'translateY(-50%)',
            backgroundColor: 'white',
            '&:hover': { backgroundColor: '#f0f0f0' },
            zIndex: 1,
          }}
        >
          {isPanelOpen ? <ChevronRightIcon /> : <ChevronLeftIcon />}
        </IconButton>
        
        <Paper
          sx={{
            width: isPanelOpen ? '400px' : '0px',
            height: '100%',
            overflow: 'hidden',
            transition: 'width 0.3s ease',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
            <Tabs value={currentTab} onChange={handleTabChange}>
              <Tab icon={<TextFieldsIcon />} label="文字" />
              <Tab icon={<AutoAwesomeIcon />} label="装饰" />
            </Tabs>
          </Box>

          <Box sx={{ flexGrow: 1, overflow: 'auto', p: 2 }}>
            {currentTab === 0 ? (
              // 文字编辑面板
              <Box>
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  label="输入文字"
                  value={text}
                  onChange={handleTextChange}
                  variant="outlined"
                  sx={{ mb: 2 }}
                />
                <FormControl fullWidth sx={{ mb: 2 }}>
                  <InputLabel>模板风格</InputLabel>
                  <Select
                    value={selectedTemplate.id}
                    onChange={handleTemplateChange}
                    label="模板风格"
                  >
                    {templates.map((template) => (
                      <MenuItem key={template.id} value={template.id}>
                        {template.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl fullWidth sx={{ mb: 2 }}>
                  <InputLabel>图片比例</InputLabel>
                  <Select
                    value={aspectRatio.id}
                    onChange={handleAspectRatioChange}
                    label="图片比例"
                  >
                    {aspectRatios.map((ratio) => (
                      <MenuItem key={ratio.id} value={ratio.id}>
                        {ratio.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl fullWidth sx={{ mb: 2 }}>
                  <InputLabel>字体</InputLabel>
                  <Select
                    value={selectedFont.id}
                    onChange={handleFontChange}
                    label="字体"
                  >
                    {fonts.map((font) => (
                      <MenuItem key={font.id} value={font.id}>
                        {font.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl fullWidth sx={{ mb: 2 }}>
                  <InputLabel>字体大小</InputLabel>
                  <Select
                    value={selectedFontSize.id}
                    onChange={handleFontSizeChange}
                    label="字体大小"
                  >
                    {fontSizes.map((size) => (
                      <MenuItem key={size.id} value={size.id}>
                        {size.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <Box sx={{ mb: 2 }}>
                  <InputLabel>文字颜色</InputLabel>
                  <input
                    type="color"
                    value={textColor}
                    onChange={handleTextColorChange}
                    style={{ width: '100%', height: '40px' }}
                  />
                </Box>
                <Box sx={{ mb: 2 }}>
                  <Typography gutterBottom>文字对齐</Typography>
                  <ToggleButtonGroup
                    value={textAlign}
                    exclusive
                    onChange={handleTextAlignChange}
                    aria-label="text alignment"
                    fullWidth
                  >
                    {textAlignments.map((alignment) => (
                      <ToggleButton key={alignment.id} value={alignment.value}>
                        {alignment.icon}
                      </ToggleButton>
                    ))}
                  </ToggleButtonGroup>
                </Box>
                <Box sx={{ mb: 2 }}>
                  <Typography gutterBottom>字间距</Typography>
                  <Slider
                    value={letterSpacing}
                    onChange={handleLetterSpacingChange}
                    min={-2}
                    max={10}
                    step={0.5}
                    valueLabelDisplay="auto"
                    valueLabelFormat={(value) => `${value}px`}
                  />
                </Box>
                <Box sx={{ mb: 2 }}>
                  <Typography gutterBottom>行高</Typography>
                  <Slider
                    value={lineHeight}
                    onChange={handleLineHeightChange}
                    min={1}
                    max={3}
                    step={0.1}
                    valueLabelDisplay="auto"
                  />
                </Box>
                <Box sx={{ mb: 2 }}>
                  <Typography gutterBottom>文字阴影</Typography>
                  <Grid container spacing={2} alignItems="center">
                    <Grid item>
                      <Button
                        variant={textShadow ? "contained" : "outlined"}
                        onClick={handleTextShadowToggle}
                      >
                        {textShadow ? "关闭阴影" : "开启阴影"}
                      </Button>
                    </Grid>
                    {textShadow && (
                      <Grid item xs>
                        <input
                          type="color"
                          value={textShadowColor}
                          onChange={handleTextShadowColorChange}
                          style={{ width: '100%', height: '40px' }}
                        />
                      </Grid>
                    )}
                  </Grid>
                </Box>
              </Box>
            ) : (
              // 装饰元素面板
              <DecorationPanel />
            )}
          </Box>

          <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
            <Button
              fullWidth
              variant="contained"
              onClick={handleDownload}
              disabled={!text}
            >
              下载图片
            </Button>
          </Box>
        </Paper>
      </Box>
    </Box>
  );
}

export default ImageEditor;
